package com.kmproject.haifu.mvp.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Description:监听TextView的左右Drawable点击事件
 * Created by Kevin.Lee on 2019-08-13.
 */
public class MonitorDrawableEventTextView extends android.support.v7.widget.AppCompatTextView {
    private OnDrawableClickListener mOnDrawableClickListener;

    public MonitorDrawableEventTextView(Context context) {
        super(context);
        setClickable(true);
    }

    public MonitorDrawableEventTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setClickable(true);
    }

    public MonitorDrawableEventTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setClickable(true);
    }

    public void setOnDrawableClickListener(OnDrawableClickListener mOnDrawableClickListener) {
        this.mOnDrawableClickListener = mOnDrawableClickListener;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {// 获取点击时手指抬起的X坐标
            int xUp = (int) event.getX();
            // 当点击的坐标到当前输入框右侧的距离小于等于getCompoundPaddingRight()的距离时，则认为是点击了删除图标
            // getCompoundPaddingRight()的说明：Returns the right padding of the
            // view, plus space for the right Drawable if any.
            if (xUp <= getCompoundPaddingStart()) {
                if (mOnDrawableClickListener != null) {
                    mOnDrawableClickListener.onStartClick();
                    return true;
                }
            } else if ((getWidth() - xUp) <= getCompoundPaddingEnd()) {
                if (mOnDrawableClickListener != null) {
                    mOnDrawableClickListener.onEndClick();
                    return true;
                }
            }
        }
        return super.onTouchEvent(event);
    }

    public interface OnDrawableClickListener {
        /**
         * 点击左侧图标
         */
        default void onStartClick() {
        }

        /**
         * 点击右侧图标
         */
        default void onEndClick() {
        }
    }
}
